<template>
  <view
    class="integral-box"
    :style="{ backgroundImage: `url(${ossImg('icons/biscuit/bg2.png')})` }"
  >
    <!--  header bg  -->
    <image
      class="header-bg"
      :src="ossImg('icons/biscuit/bg1.png')"
      :style="{ marginTop: `-64px` }"
    />
    <view class="title-content mt-40px">
      <view class="px-36px">
        <image
          class="w-181px h-82px"
          :src="ossImg('icons/biscuit/header_title.png')"
        ></image>
      </view>
      <view class="px-44px py-10px">
        <view
          class="light-text font-bold text-13px leading-none tracking-1px"
          v-html="textHtml"
        ></view>
        <view
          class="flex items-end leading-none h-26px font-bold mt-7px mb-6px"
        >
          <text
            class="light-text text-34px leading-26px"
            @click.stop="linkTo('/personalPages/biscuit/biscuit')"
            >{{ user.memberScore.surplusScore || 0 }}</text
          >
          <text class="light-text text-12px w-14px text-center">/</text>
          <image
            class="w-20px h-24px"
            :src="ossImg('icons/biscuit/oreo.png')"
          />
        </view>
        <view class="mall-go light-text" @click.stop="toBiscuitMall">
          <image :src="ossImg('icons/biscuit/mall.png')" />
          前往积分商城
        </view>
      </view>
    </view>
    <view class="play w-full flex flex-col items-center justify-center">
      <image
        class="w-160px h-48px"
        :src="ossImg('biscuit/wyw_but.png')"
        @click="linkTo('/integralPages/integral/sign')"
      />
      <text
        class="light-text text-s font-bold leading-none mt-7px tracking-2px"
        @click.stop="toRule"
        >小饼干规则</text
      >
    </view>
    <view class="task">
      <image
        class="w-280px h-64px mb-13px"
        :src="ossImg('icons/biscuit/title.png')"
      />
      <scroll-box :height="taskListHeight">
        <view class="task-list">
          <view class="task-card" v-for="item in taskList" :key="item">
            <view class="task-content leading-none">
              <view class="px-8px" style="position: relative; z-index: 2">
                <view class="flex items-center text-yellow text-14px h-24px">
                  <image
                    class="w-20px h-16px"
                    :src="ossImg('icons/biscuit/task.png')"
                  />
                  {{ item.name }}
                </view>
                <view class="pb-6px text-white text-xxs"
                  >{{ item.description }}
                </view>
              </view>
            </view>

            <view class="task-go" @click.stop="goTask(item)">
              <template v-if="item.code === 'invite'">
                <button open-type="share">
                  <image
                    :src="
                      item.completed
                        ? ossImg('integral/grey_bg.png')
                        : ossImg('integral/yellow_bg@2x.png')
                    "
                  />
                  <text>{{ switchBtn(item) }}</text>
                </button>
              </template>
              <template v-else>
                <image
                  :src="
                    item.completed
                      ? ossImg('integral/grey_bg.png')
                      : ossImg('integral/yellow_bg@2x.png')
                  "
                />
                <text>{{ switchBtn(item) }}</text>
              </template>
            </view>
          </view>
        </view>
      </scroll-box>
    </view>
    <button open-type="contact" @click.stop="toKefu">
      <view class="oreo-service">
        <image :src="ossImg('personal/kf_icon@2x.png')" />客服
      </view>
    </button>
  </view>

  
</template>

<script setup>
import { ossImg, setCurrentTabBar, message } from "@/utils/utils";
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import ScrollBox from "@/components/scroll-box";
import { getTaskList } from "@/services/integral";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const textHtml = "&lt;我的小饼干>";
const statusBarHeight = ref(getApp().globalData.statusBarHeight);
const taskListHeight = ref(0);
const user = ref(getApp().globalData.user);
const taskList = ref([]);

onShow(() => {
  setCurrentTabBar(1, false);
  // 用户进入时间
  enterTime = new Date();
  getList();
  if (uni.getStorageSync("TOKEN")) {
    getApp()
      .getUserInfo()
      .then((res) => {
        user.value = res;
      });
  }
  getApp()
    .getUserInfo()
    .then((res) => {
      user.value = res;
    });
  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;

  getApp().emdlz(
    "track",
    "event",
    "pointspage",
    "view",
    "pointspage",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "pointspage",
    "view",
    "pointspage",
    stayTime
  );
});

onLoad(() => {
  // uni.hideTabBar()
  //#ifdef MP-WEIXIN
  wx.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
  //#endif
  const taskList = uni.createSelectorQuery().select(".task-list");
  taskList
    .boundingClientRect((result) => {
      taskListHeight.value = result.height * 2;
    })
    .exec();
});

const getList = async () => {
  const res = await getTaskList();
  if (res?.code === 200) {
    taskList.value = res.data;
  }
};

onShareAppMessage((e) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1].route;
  const pageUrl = "/pages/home/home" + "?id=" + getApp().globalData.user.id;
  const shareObj = {
    title: "", // 默认是小程序的名称(可以写slogan等)
    path: pageUrl, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: "", //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});

const linkTo = (url) => uni.navigateTo({ url });

// const goGame = () => {
//   getApp().emdlz("track", "event", "pointspage", "click", "daily_change", "");
//   message("开发中~");
// };

const toBiscuitMall = () => {
  getApp().emdlz("track", "event", "pointspage", "click", "points_mall2", "");
  linkTo("/personalPages/biscuit/mall");
};

const goTask = (item) => {
  if (item.completed) return;
  switch (item.code) {
    case "information":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "profile_submit",
        ""
      );
      uni.navigateTo({ url: "/personalPages/personalInfo/index" });
      break;

    case "purchase":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "cart_accomplish",
        ""
      );
      uni.switchTab({ url: "/pages/mall/mall" });
      break;

    case "register":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "become_oreo_player",
        ""
      );
      uni.navigateTo({ url: "/pages/vip/register" });
      break;

    case "subOreo":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "follow_official_wechat_account",
        ""
      );
      uni.navigateTo({
        url: "/pages/webView/webview?webSrc=https://mp.weixin.qq.com/s/T6ThaRY-yimSkm0b2pH2Tg",
      });
      break;

    case "firstBuy":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "oreo_accomplish",
        ""
      );
      uni.switchTab({ url: "/pages/mall/mall" });
      break;

    case "rArticle":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "read_article",
        ""
      );
      uni.navigateTo({ url: "/integralPages/integral/consultingList" });
      break;

    case "invite":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "invite_friends",
        ""
      );
      break;

    case "miniGame":
      getApp().emdlz("track", "event", "pointspage", "click", "game_play", "");
      message("开发中~");
      break;

    case "dBrowse":
      getApp().emdlz(
        "track",
        "event",
        "pointspage",
        "click",
        "daily_view_accomplish",
        ""
      );
      uni.switchTab({ url: "/pages/mall/mall" });
      break;

    case "sign":
      getApp().emdlz("track", "event", "pointspage", "click", "sign_in", "");
      uni.navigateTo({ url: "/integralPages/integral/sign" });
      break;
  }
};

const toRule = () => {
  getApp().emdlz("track", "event", "pointspage", "click", "biscuit_rule", "");
  linkTo("/integralPages/integral/rule");
};

const switchBtn = (item) => {
  let text = "";
  if (item.completed) return "已完成";
  switch (item.code) {
    case "information":
      text = "去完善";
      break;

    case "purchase":
      text = "去购买";
      break;

    case "register":
      text = "去注册";
      break;

    case "subOreo":
      text = "去关注";
      break;

    case "firstBuy":
      text = "去购买";
      break;

    case "rArticle":
      text = "去学习";
      break;

    case "invite":
      text = "去邀请";
      break;

    case "miniGame":
      text = "去玩游戏";
      break;

    case "dBrowse":
      text = "去浏览";
      break;

    case "sign":
      text = "去签到";
      break;

    default:
      break;
  }

  return text;
};
const toKefu = () => {
  getApp().emdlz("track", "event", "homepage", "click", "customer_service", "");
  getApp().sr().track("start_consult", {
    action_type: "consult_online",
    // more...
  });
};
</script>

<style lang="less" scoped>
.task {
  box-sizing: border-box;
  padding: 23px 26px 32px 50px;
  display: flex;
  flex: 1;
  flex-direction: column;

  .task-list {
    width: 100%;
    height: 300px;

    /* 全局滚动条样式统一 */
    .task-card {
      display: flex;
      position: relative;
      margin-right: 18px;
      margin-bottom: 20px;

      .task-content {
        width: 175px;
        height: 40px;
        background-color: green;

        &::before {
          content: "";
          width: inherit;
          border-top: 40px solid #0084ff;
          border-right: 20px solid transparent;
          position: absolute;
          left: 0;
          top: 0;
          z-index: 1;
        }

        &::after {
          content: "";
          width: inherit;
          border-top: 40px solid #00081d;
          border-right: 20px solid transparent;
          position: absolute;
          left: 5px;
          top: 7px;
          z-index: 0;
          opacity: 0.3;
        }
      }

      .task-go {
        width: 100px;
        height: 55px;
        position: absolute;
        right: 0;
        top: -10px;
        color: #114de4;
        font-size: 13px;
        display: flex;
        align-items: center;
        justify-content: center;

        button {
          width: 100%;
          height: 100%;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 0;
          line-height: 1;
          color: #114de4;
          font-size: 13px;
          background-color: transparent;

          &::after {
            border: none;
          }
        }

        text {
          position: relative;
          z-index: 1;
          margin-top: -5px;
          margin-right: -2px;
        }

        image {
          width: inherit;
          height: inherit;
          position: absolute;
        }
      }
    }
  }
}

.integral-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-size: 100% 835px;
  background-position: top 236px right 0;
  background-repeat: no-repeat;
  color: #ffffff;

  .header-bg {
    width: 100%;
    height: 375px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
  }

  .mall-go {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 128px;
    width: 128px;
    height: 28px;
    padding: 0 4px 0 0;
    border: 1px solid #fffffa;
    border-radius: 7px;
    color: white;
    font-size: 16px;
    box-sizing: border-box;
    white-space: nowrap;

    image {
      width: 24px;
      height: 24px;
    }
  }
}

image {
  display: block;
}

.light-text {
  position: relative;
  text-shadow: 0 0 15px #ffd800, 0 0 7px #ffd800;
}
</style>
